from django.http import JsonResponse
import datetime, random
from cimp.settings import UPLOAD_DIR


def upload_handle(request):
    if not request.user.is_authenticated:
        return JsonResponse(
            {'ret': 1, 'msg': '未登录'}, json_dumps_params={'ensure_ascii': False})
    if request.method == 'POST':
        # FILES中Key是<input type="file" name="" />标签中name属性的值
        uploadFile = request.FILES['upload1']
        filetype = uploadFile.name.split('.')[-1]
        filesize = uploadFile.size
        if filetype not in ['jpg', 'png']:
            return JsonResponse(
                {'ret': 1, 'msg': '图片类型错误'}, json_dumps_params={'ensure_ascii': False})
        if filesize > 10*1024*1024:
            return JsonResponse(
                {'ret': 1, 'msg': '图片大于10M'}, json_dumps_params={'ensure_ascii': False})
        userid = request.user.id
        timestamp = datetime.datetime.now().strftime('%Y%m%d%I%M%S')
        randomnum = random.randint(1, 999999)
        filename = f'{userid}_{timestamp}_{randomnum}.{filetype}'
        with open(f'{UPLOAD_DIR}/{filename}', 'wb') as f:
            for chunk in uploadFile.chunks():
                f.write(chunk)
        return JsonResponse({'ret': 0, 'url': f'/upload/{filename}'})